<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="cn">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.0.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.0.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.0.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.0.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.0.0" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta property="og:type" content="website">
<meta property="og:title" content="categories">
<meta property="og:url" content="http://yoursite.com/categories/index.html">
<meta property="og:site_name" content="hill&#39;s blog">
<meta property="og:locale" content="cn">
<meta property="article:published_time" content="2017-07-10T08:36:26.000Z">
<meta property="article:modified_time" content="2021-02-25T04:04:48.836Z">
<meta property="article:author" content="heyaojia">
<meta name="twitter:card" content="summary">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.0.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/categories/"/>





  <title>Mysql/MYSQL-索引 | hill's blog</title>
  








<meta name="generator" content="Hexo 4.2.1"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="cn">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> <div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">hill's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            Categories
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2021/05/08/Mysql/MYSQL-%E7%B4%A2%E5%BC%95/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="heyaojia">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="hill's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Mysql/MYSQL-索引</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2021-05-08T10:37:23+08:00">2021-05-08</time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="MYSQL-索引"><a href="#MYSQL-索引" class="headerlink" title="MYSQL - 索引"></a><strong><em>MYSQL</em></strong> - 索引</h3><hr>
<h5 id="一、索引基本概述"><a href="#一、索引基本概述" class="headerlink" title="一、索引基本概述"></a><strong>一、索引基本概述</strong></h5><p>​        众所周知，索引是<strong><em>Mysql</em></strong>中很重要的一个系统。如果没有索引的存在，那么我们在查询数据的时候，必须得整表遍历，直至找到对应数据。那么一个既要在时间复杂度和空间复杂的度都快速的索引系统设计，是至关重要的。本文目的是为了详细搞懂索引的相关原理，以及实际业务场景中的一些问题。</p>
<h5 id="二、索引原理"><a href="#二、索引原理" class="headerlink" title="二、索引原理"></a><strong>二、索引原理</strong></h5><p><strong><em>|1. 相关概念（操作系统）</em></strong></p>
<ol>
<li><p>计算机操作系统中局部性原理</p>
<p>​    <img src="https://pic1.zhimg.com/80/v2-1d4036e0bf980a34f94d6ab414f3ae17_720w.jpg?source=1940ef5c" alt="图来自知乎"></p>
<p>​    按照上图操作系统存储速度对照表，数据是放在越上层运行速度越快，同时容量也越小，所以这少不了不同层数之间会存在数据交换。CPU从缓存读取数据读取不到的时候（缓存未命中），会k + 1层去获取数据，直到最后一层，这样大大降低了CPU的效率，所以在编写程序的时候，具有局部性原理的数据，会更有效率。程序都有聚集成群的倾向，分为空间局部性和时间局部性：</p>
<ol>
<li><p>时间局部性原理</p>
<p>​    <code>同一内存地址，多次被访问到，称之为时间局部性</code></p>
</li>
<li><p>空间局部性原理</p>
<p>​    <code>如果一个内存地址被引用后，与他相邻的附近的内存地址也被引用了，这就是空间局部性原理</code></p>
</li>
</ol>
<ul>
<li><a href="https://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-processing-an-unsorted-array" target="_blank" rel="noopener">stackoverflow关于代码中有序Array和无序数组的局部性</a></li>
<li><a href="https://www.zhihu.com/question/25142664" target="_blank" rel="noopener">知乎中关于局部性原理的讨论</a></li>
</ul>
</li>
<li><p>磁盘预读</p>
<p>​    内存跟磁盘交互的时候保证每次读取一个逻辑单位，这个逻辑单位叫做页，或者叫page，一般都是4k或者8k，在进行读取的时候都是4K的整数倍，InnoDB一次读取16KB的数据。</p>
</li>
</ol>
<p><strong><em>|2. Mysql索引的数据结构</em></strong></p>
<ul>
<li>思考: 降低I/O的方式有以下两个方面<ul>
<li>I/O次数</li>
<li>I/O读取的量级</li>
</ul>
</li>
</ul>
<ol>
<li><p>可以作为索引的数据结构..</p>
<p>​    <strong><em>Mysq</em></strong>l中索引的使用时，有Hash和二叉树、B树、B+树</p>
<ol>
<li><p>哈希索引</p>
<p>在<strong><em>Mysql</em></strong>中，哈希索引只在Memory引擎中使用显式哈希（在内存，效率较高）。InnoDB支持自适应的哈希。</p>
<p>哈希索引的优点：</p>
<ol>
<li>哈希索引自身只需存储对应的hash值，索引的机构十分紧凑，所以非常快</li>
</ol>
<p>哈希索引的限制：</p>
<ol>
<li>哈希索引只包含哈希值和指针，不存字段</li>
<li>哈希索引的数据不是按照索引值顺序存放，是离散的，所以无法排序</li>
<li>哈希索引不支持部分列查找，需要全部内容来哈希</li>
<li>不支持范围查询</li>
<li>访问虽快，但是哈希碰撞的时候（Java的HashMap中算法叫扰动算法），必须要遍历列表所有指针，逐行检查</li>
<li>碰撞越多，维护成本越大</li>
</ol>
</li>
<li><p>树型索引</p>
<p><strong><em>|1 二叉树</em></strong> </p>
<p>​    <img src="....%5Cimages%5CMysql%E7%B4%A2%E5%BC%95%E6%80%BB%E7%BB%93%5Cimage-20210425215707721.png" alt="image-20210425215707721"></p>
<p><strong><em>|2 红黑树</em></strong></p>
<p>​     <img src="....%5Cimages%5CMysql%E7%B4%A2%E5%BC%95%E6%80%BB%E7%BB%93%5Cimage-20210425215713988.png" alt="image-20210425215713988"></p>
<p>（以上树的节点都会无限加深，会提升IO次数）</p>
<p><strong><em>|3 B-树、B+树</em></strong></p>
<ol>
<li><p>B-树</p>
<p><img src="....%5Cimages%5CMysql%E7%B4%A2%E5%BC%95%E6%80%BB%E7%BB%93%5Cimage-20210425220408425.png" alt="image-20210425220408425"></p>
<p>eg：定位建值为28的数据</p>
<ol>
<li>在第一个块16k的数据找到指针p2（root节点在内存）</li>
<li>读到第二块16k数据找到指针p2</li>
<li>最终找到磁盘块8</li>
</ol>
<ul>
<li>可存储数据 = （假设data一个1k）一块16个索引，16 * 16 * 16 = 4096条，可见是无法满足实际业务需要的，所以B+树就来了</li>
</ul>
</li>
<li><p>B+树     </p>
<p><img src="....%5Cimages%5CMysql%E7%B4%A2%E5%BC%95%E6%80%BB%E7%BB%93%5Cimage-20210425221219820.png" alt="image-20210425221219820"></p>
<ul>
<li>可存储数据为假设key一个10字节 一块16k1600条数据，1600 * 1600 * 16 = 40,960,000条(千万级别)</li>
</ul>
</li>
</ol>
</li>
</ol>
</li>
<li><p><strong><em>B+树</em></strong>在InnoDB中的使用（具体B+树的原理不在这里赘述）</p>
<p><img src="....%5Cimages%5CMysql%E7%B4%A2%E5%BC%95%E6%80%BB%E7%BB%93%5Cclipboard.png" alt="img"></p>
<ul>
<li>优点 -&gt;<ul>
<li>多叉树，多个子节点</li>
<li>叶子节点有序</li>
<li>每个节点可以存多个数据</li>
<li>是一颗平衡二叉树</li>
</ul>
</li>
<li>常见问题 -&gt;</li>
</ul>
</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">1、mysql的索引一版有几层？</span><br><span class="line">一般情况下，3到4层足以支撑千万级别的表查询，层数是由索引值大小来控制的，所以选取索引的时候一般用占用空间小的</span><br><span class="line"></span><br><span class="line">2、创建索引的字段是长的好，还是短的好？</span><br><span class="line">短的好，因为一块16k，层数不变的情况下，越小存的节点数量越多</span><br><span class="line"></span><br><span class="line">3、创建表的时候用代理主键，还是用自然主键</span><br><span class="line">能使用代理主键尽可能多的使用代理主键</span><br><span class="line"></span><br><span class="line">4、主键设置好，要不要自增？</span><br><span class="line">在满足业务的情况下，尽可能自增，不自增会增加索引维护的成本</span><br><span class="line"></span><br><span class="line">5、分布式应用场景中，自增ID适用吗？</span><br><span class="line">雪花算法 snowflake，自定义id生成器</span><br></pre></td></tr></table></figure>



<p><strong><em>|3. InnoDB下的索引分类</em></strong></p>
<ol>
<li><p><strong>聚镞索引</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">&#96;&#96;&#96;规则：主键索引就是聚族索引，必须包含一个主键列，那么key就是主键，如果没有主键，那么key就是唯一键，如果没有唯一键，key就是6字节的rowid</span><br></pre></td></tr></table></figure>



</li>
</ol>
<ol start="2">
<li><p><strong>非聚镞索引</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">&#96;&#96;&#96;规则:MYISAM都是非聚镞索引In弄DB的二级索引（辅助、普通索引）</span><br></pre></td></tr></table></figure>

<p><img src="../../images/Mysql%E7%B4%A2%E5%BC%95%E6%80%BB%E7%BB%93/image-20210425182857637.png" alt="image-20210425182857637"></p>
</li>
<li><p><strong>唯一索引</strong>（主键是唯一索引）</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">4. **第二索引**(普通索引)</span><br><span class="line"></span><br><span class="line">   &#96;&#96;&#96;InnoDB中，普通索引的规则是，叶子节点存放的是主键的值,不需要回到主键树上去找，这叫做覆盖索引</span><br></pre></td></tr></table></figure>

<p><a href="">回表</a></p>
<p><a href="">索引覆盖</a></p>
</li>
<li><p><strong>组合索引</strong></p>
<p><code>InnoDB中，索引可以是多个值组成的复合索引，也叫组合索引，组合索引必须谈到最左匹配</code></p>
</li>
<li><p><strong>全文索引</strong></p>
<p>​    （用的较少，后面再补充，这是网上博客的一些描述）</p>
<p>　　全文索引的对象是一个“全文集合”，如果对表的多个列建立全文索引，MYSQL就会将这几列拼接成一个字符串，然后进行索引。全文索引实际上也是B+ Tree结构，不过比较特殊，它一共有两层，第一层是所有的关键字，第二层则是每个关键字的一组指文档针，例如 “X” -&gt;行1，行2，行3……。通俗解释全文索引结构就是：它是以关键字去找文档（行），而不是像其他一些索引以行主键来找其他列的内容。要使用全文索引，关于它的几个参数的意义一定要清楚，控制全文索引的参数都是以 ft 开头的（FullText）。查看这些参数以及它们的意义</p>
</li>
</ol>
<p><strong><em>|4. 索引相关概念</em></strong></p>
<ul>
<li>准备： 建立一张名为p，有 id age name address字段的表</li>
</ul>
<ol>
<li>回表</li>
</ol>
<ol start="2">
<li><p>索引覆盖</p>
<ul>
<li>资料：<ul>
<li><a href="https://www.cnblogs.com/happyflyingpig/p/7662881.html" target="_blank" rel="noopener">索引覆盖的概念及其索引优化举例</a></li>
</ul>
</li>
</ul>
</li>
<li><p>最左匹配</p>
</li>
</ol>
<ul>
<li>资料：<ul>
<li><a href="https://zhuanlan.zhihu.com/p/115778804" target="_blank" rel="noopener">知乎关于组合索引最左匹配的描述</a></li>
</ul>
</li>
</ul>
<ol start="4">
<li><p>索引下推</p>
<p>​    </p>
<ul>
<li>资料<ul>
<li><a href="https://zhuanlan.zhihu.com/p/121084592" target="_blank" rel="noopener">知乎：什么是索引下推</a></li>
<li><a href="https://blog.csdn.net/sinat_29774479/article/details/103470244" target="_blank" rel="noopener">博客：图解索引下推</a></li>
</ul>
</li>
</ul>
</li>
<li><p>谓词下推</p>
</li>
</ol>
<p><strong><em>|6.索引优化</em></strong></p>
<ol>
<li><p>MYSQL中Explain语句查看是否有用索引</p>
</li>
<li><p>尽量使用索引</p>
</li>
<li><p>避免回表</p>
</li>
</ol>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/kity@2.0.4/dist/kity.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/kityminder-core@1.4.50/dist/kityminder.core.min.js"></script><script defer="true" type="text/javascript" src="https://cdn.jsdelivr.net/npm/hexo-simple-mindmap@0.2.0/dist/mindmap.min.js"></script><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/hexo-simple-mindmap@0.2.0/dist/mindmap.min.css">
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2021/05/07/%E5%B7%A5%E5%85%B7%E5%BA%94%E7%94%A8/MakeFile/" rel="next" title="Makefile学习">
                <i class="fa fa-chevron-left"></i> Makefile学习
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">heyaojia</p>
              <p class="site-description motion-element" itemprop="description">游戏行业的一枚小鲜肉</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">21</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">5</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="git@gitee.com:hillcool/hillcool.git" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-gitee"></i>GitHub</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#MYSQL-索引"><span class="nav-number">1.</span> <span class="nav-text">MYSQL - 索引</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#一、索引基本概述"><span class="nav-number">1.0.1.</span> <span class="nav-text">一、索引基本概述</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#二、索引原理"><span class="nav-number">1.0.2.</span> <span class="nav-text">二、索引原理</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">heyaojia</span>

  

  
</div>









        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>
























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.0.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.0.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.0.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.0.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.0.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.0.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.0.0"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
